<?php

namespace common\models\db;

use Yii;
use wodrow\yii2wtools\tools\ArrayHelper;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yiithings\softdelete\SoftDelete;

/**
 * This is the model class for table "{{%admin_role}}".
 *
 * @author
 * @property-read array $statusDesc
 * @property AdminRolePower[] $adminRolePowers
 * @property AdminPower[] $adminPowers
 */
class AdminRole extends \common\models\db\tables\AdminRole
{
    const SCENARIO_TEST = 'test';
    const STATUS_ACTIVE = 10;

    public function getStatusDesc()
    {
        return [
            self::STATUS_ACTIVE => "正常",
        ];
    }

    public static function getAllRoles()
    {
        $list = static::find()->all();
        return $list;
    }

    use SoftDelete;

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors = ArrayHelper::merge($behaviors, [
            'timestamp' => [
                'class' => TimestampBehavior::class,
            ],
            'blameable' => [
                'class' => BlameableBehavior::class,
            ],
            'softdelete' => [
                'class' => 'yiithings\softdelete\behaviors\SoftDeleteBehavior',
            ],
        ]);
        return $behaviors;
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios = ArrayHelper::merge($scenarios, [
            self::SCENARIO_TEST => [],
        ]);
        return $scenarios;
    }

    public function rules()
    {
        $rules = parent::rules();
        foreach ($rules as $k => $v) {
            if ($v[1] == 'required'){
                $rules[$k][0] = array_diff($rules[$k][0], ['created_at', 'updated_at', 'created_by', 'updated_by']);
            }
        }
        $rules = ArrayHelper::merge($rules, [
//            [[], 'required', 'on' => self::SCENARIO_TEST],
        ]);
        return $rules;
    }

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, [
            'name' => "角色名",
            'created_at' => "创建时间",
            'status' => "状态",
        ]);
        return $attributeLabels;
    }

    public function beforeValidate()
    {
        if (parent::beforeValidate()){
            // TODO: Change the autogenerated stub
            return true;
        }else{
            return false;
        }
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)){
            $this->user_total = AdminUserRole::find()->where(['admin_role_id' => $this->id])->count();
            return true;
        }else{
            return false;
        }
    }

    public function beforeDelete()
    {
        if (parent::beforeDelete()){
            if ($this->adminRolePowers){
                return false;
            }
            return true;
        }else{
            return false;
        }
    }

    public function afterFind()
    {
        parent::afterFind();
        // TODO: Change the autogenerated stub
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        // TODO: Change the autogenerated stub
    }

    public function afterValidate()
    {
        parent::afterValidate();
        // TODO: Change the autogenerated stub
    }

    public function afterRefresh()
    {
        parent::afterRefresh();
        // TODO: Change the autogenerated stub
    }

    public function afterDelete()
    {
        parent::afterDelete();
        // TODO: Change the autogenerated stub
    }

    public function test()
    {
        $test = self::instance();
        $test->setScenario(self::SCENARIO_TEST);
        $test->save();
        var_dump($test->toArray());
    }

    public function getAdminRolePowers()
    {
        return $this->hasMany(AdminRolePower::class, ['admin_role_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery|AdminPower[]
     * @throws \yii\base\InvalidConfigException
     */
    public function getAdminPowers()
    {
        return $this->hasMany(AdminPower::class, ['id' => 'admin_power_id'])->viaTable(AdminRolePower::tableName(), ['admin_role_id' => "id"]);
    }

    public function getAdminPowerIds()
    {
        $ids = [];
        foreach ($this->adminPowers as $k => $v){
            $ids[] = $v->id;
        }
        return $ids;
    }

    /**
     * @return AdminPower[]
     */
    public function getCheckedAdminPowers($toArray = 0)
    {
        $list = [];
        foreach (AdminPower::getAllPowers() as $k => $v) {
            if ($toArray){
                $data = $v->toArray();
                if (in_array($v->id, $this->getAdminPowerIds())){
                    $data['isChecked'] = 1;
                }else{
                    $data['isChecked'] = 0;
                }
                $data['data_rule'] = AdminRolePower::DATA_RULE_ALL;
                $adminRolePower = AdminRolePower::findOne(['admin_role_id' => $this->id, 'admin_power_id' => $v->id]);
                if ($adminRolePower)$data['data_rule'] = $adminRolePower['data_rule'];
            }else{
                $data = $v;
            }
            $list[] = $data;
        }
        return  $list;
    }

    public function getCheckedAdminPowerIds()
    {
        $ids = [];
        foreach ($this->getCheckedAdminPowers() as $k => $v){
            $ids[] = $v->id;
        }
        return $ids;
    }

    /**
     * @return AdminPower[]
     */
    public function getAdminMenus()
    {
        $list = [];
        foreach ($this->getAdminPowers() as $k => $v) {
            if ($v->type == AdminPower::TYPE_MENU){
                $list[] = $v;
            }
        }
        return $list;
    }

    public function getAdminFuns()
    {
        $list = [];
        foreach ($this->getAdminPowers() as $k => $v) {
            if ($v->type == AdminPower::TYPE_FUN){
                $list[] = $v;
            }
        }
        return $list;
    }

    public function getCheckedAdminMenuFunTree()
    {
        $menus = $funs = [];
        foreach (AdminPower::getAllPowers() as $k => $v) {
            $power = $v->toArray();
            if (in_array($v->id, $this->getAdminPowerIds())){
                $power['isChecked'] = 1;
            }else{
                $power['isChecked'] = 0;
            }
            switch ($v->type){
                case AdminPower::TYPE_MENU:
                    $menus[] = $power;
                    break;
                default:
                    $funs[] = $power;
                    break;
            }
        }
        return AdminPower::generateMenuFunTree($menus, $funs);
    }
}
